package com.air.ota.util;

import hsmj.HsmApp;
import hsmj.HsmConst;

public class HsmjUtil {
	
	public static final byte _ENCRYPT_FLAG = (byte)0x91;
	public static final byte _DECRYPT_FLAG = (byte)0x92;
	
	
	synchronized public static byte[] encrypt(byte[] cardSequence,byte[] random,byte[] data){
		int iKekIndex = 0;
		
		HsmApp hApp = new HsmApp();
		
		random = HexStringUtil.hexStringToBytes(HexStringUtil.bytesToHexString(random)+"20202020");
		byte[] devdata = new byte[cardSequence.length+random.length];
		System.arraycopy(cardSequence, 0, devdata, 0, 8);
		System.arraycopy(random, 0, devdata, 8, 8);
		
		int[] dataOutlen = new int[1];
		byte[] dataOut = new byte[1024];
		
		int nRet = -1;
		while (nRet!= HsmConst.T_SUCCESS){
			nRet = hApp.HSMEncryptBySHSMK(iKekIndex, 2, devdata, data.length, data, dataOutlen, dataOut,_ENCRYPT_FLAG);
			System.out.println("Trying encrypt using HSMJ,result="+nRet);
		}
		
		int outLen = dataOutlen[0];
		byte[] finalData = new byte[outLen];
		System.arraycopy(dataOut, 0, finalData, 0, outLen);
		
		return finalData;
	}
	
	synchronized public static byte[] decrypt(byte[] cardSequence,byte[] random,byte[] data){
		int iKekIndex = 0;
		
		HsmApp hApp = new HsmApp();
		
		random = HexStringUtil.hexStringToBytes(HexStringUtil.bytesToHexString(random)+"20202020");
		byte[] devdata = new byte[cardSequence.length+random.length];
		System.arraycopy(cardSequence, 0, devdata, 0, 8);
		System.arraycopy(random, 0, devdata, 8, 8);
		
		int[] dataOutlen = new int[1];
		byte[] dataOut = new byte[1024];
		
		int nRet = -1;
		while (nRet!= HsmConst.T_SUCCESS){
			nRet = hApp.HSMEncryptBySHSMK(iKekIndex, 2, devdata, data.length, data, dataOutlen, dataOut,_DECRYPT_FLAG);
			System.out.println("Trying decrypt using HSMJ,result="+nRet);
		}
		
		int outLen = dataOutlen[0];
		byte[] finalData = new byte[outLen];
		System.arraycopy(dataOut, 0, finalData, 0, outLen);
		
		return finalData;
	}
	
	
	
	
}
